import 'dart:async';
import 'dart:convert';
import 'dart:math';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hari_curly/src/common/style.dart';
import 'package:hari_curly/src/states/device_info_state.dart';

import '../../../common/event.dart';
import '../../../states/device_connect_status.dart';

const sliderTheme = SliderThemeData(
  trackShape: RectangularSliderTrackShape(),
  trackHeight: 2.0,
  thumbShape: RoundSliderThumbShape(enabledThumbRadius: 8.0),
);

class AutoStart extends StatefulWidget {
  const AutoStart({super.key});

  @override
  State<StatefulWidget> createState() => _AutoStartState();
}

class _AutoStartState extends State<AutoStart>  with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _animation;
  final initConfig = {
    'curling': 10.0,
    'style': 10.0,
    'cold_wind': 5.0,
  };
  Map<String, double> startConfig = {
    'curling': 10.0,
    'style': 10.0,
    'cold_wind': 5.0,
  };
  bool _runFlag = false;
  var _runType = "curling";

  late Timer _timer;
  // 当前时间 0-_totalDuration
  int _time = 0;
  @override
  void initState() {
    super.initState();
    _runFlag = false;
    _runType="curling";
    _controller = AnimationController(
      duration: Duration(seconds: 10),
      vsync: this,
    )..repeat(); // 无限循环
    _animation = Tween<double>(begin: 0, end: 2 * pi).animate(_controller);
    eventBus.on<DeviceAutoStartEvent>().listen((event) {
      if(!_runFlag&&mounted){
        _autoStart();
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
    _runFlag = false;
    _runType="curling";
  }

  _showSettingDialogs(data) {
    showModalBottomSheet(
        context: context,
        // 去除点击遮罩层关闭
        isDismissible: false,
        builder: (BuildContext context) {
          Map<String, double> state = {
            'curling': 10.0,
            'style': 10.0,
            'cold_wind': 5.0,
          };
          state = {...state, ...data};
          return StatefulBuilder(
            builder: (context, setState) {
              return Container(
                  // 上面圆角
                  decoration: BoxDecoration(
                      color: pageBgColor,
                      borderRadius: BorderRadius.only(
                          topLeft: Radius.circular(20),
                          topRight: Radius.circular(20))),
                  padding: EdgeInsets.symmetric(vertical: 16, horizontal: 18),
                  constraints: BoxConstraints(minHeight: 480),
                  width: MediaQuery.of(context).size.width,
                  child: Column(children: [
                    _generateConfigCard("curling".tr(), Colors.white, 'curling', state,
                        (value) {
                      setState(() {
                        state['curling'] = value;
                      });
                    }),
                    SizedBox(width: 10, height: 10),
                    _generateConfigCard(
                        "style".tr(), Colors.purpleAccent, 'style', state, (value) {
                      setState(() {
                        state['style'] = value;
                      });
                    }),
                    SizedBox(width: 10, height: 10),
                    _generateConfigCard("cold_wind".tr(), Colors.blue, 'cold_wind', state,
                        (value) {
                      setState(() {
                        state['cold_wind'] = value;
                      });
                    }),
                    SizedBox(width: 10, height: 20),
                    Expanded(
                      child:    Row(
                          mainAxisAlignment: MainAxisAlignment.spaceAround,
                          children: [
                            RawMaterialButton(
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(5.0),
                              ),
                              fillColor: unitBgColor,
                              splashColor: Colors.black54,
                              elevation: 5,
                              textStyle: TextStyle(color: Colors.white),
                              onPressed: () {
                                setState(() {
                                  // 序列化和反序列化 深度克隆initConfig
                                  state = {...jsonDecode(jsonEncode(initConfig))};
                                });
                              },
                              child:  Text("reset".tr()),
                            ),
                            RawMaterialButton(
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(5.0),
                              ),
                              fillColor: Colors.white,
                              splashColor: Colors.grey,
                              elevation: 5,
                              textStyle: TextStyle(color: Colors.black),
                              onPressed: () {
                                Navigator.of(context).pop(state);
                              },
                              child:  Text("save".tr()),
                            )
                          ]) ,
                    )

                  ]));
            },
          );
        }).then((res) => {
          setState(() {
            if (res != null) {
              startConfig = res;
            }
          })
    });
  }

  _generateConfigCard(title, activeColor, key, state, cb) {
    return Card(
        color: unitBgColor,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(10.0),
        ),
        child: Container(
          padding: EdgeInsets.fromLTRB(0, 0, 18, 18),
          child: Column(
            children: [
              Container(
                alignment: Alignment.topLeft,
                padding: EdgeInsets.all(8),
                child: Text("${title}"),
              ),
              Row(
                children: [
                  Expanded(
                    child: SliderTheme(
                        data: sliderTheme,
                        child: Slider(
                          //调整线条的粗细
                          inactiveColor: Colors.black,
                          activeColor: activeColor,
                          key: Key('${key}'),
                          value: state['${key}']!,
                          divisions: 1000,
                          min: 1,
                          max: 30,
                          // 设置步长为1.0
                          onChanged: (double value) {
                            cb( value.floorToDouble());
                          },
                          onChangeEnd: (double value) {
                            setState(() {
                              cb( value.floorToDouble());
                            });
                          },
                        )),
                  ),
                  Container(
                    width: 30,
                    alignment: Alignment.topRight,
                    child: Text('${state['${key}']!.toInt()}',
                        style: TextStyle(fontSize: 16, color: Colors.white)),
                  ),
                ],
              )
            ],
          ),
        ));
  }

  _autoStart(){
    print('自动开始${context.read<DeviceInfoStatus>().state.writeCharacteristic}');
    if(context.read<DeviceInfoStatus>().state.writeCharacteristic==null||context.read<DeviceConnectStatus>().state.id=='-1') return;
    setState(() {
      _time=0;
      _runType='curling';
      _runFlag =true;
    });
    const timeout = Duration(seconds: 1);
    context.read<DeviceInfoStatus>().state.writeCharacteristic?.write([0xBB,0x0A,0x01]);
    HapticFeedback.vibrate();
    _timer= Timer.periodic(timeout, (timer){
      setState(() {
        _time++;
      });
      if(_time>startConfig['curling']!){
        _timer.cancel();
        setState(() {
          _time=0;
          _runType='style';
          context.read<DeviceInfoStatus>().state.writeCharacteristic?.write([0xBB,0x0A,0x00]);
          context.read<DeviceInfoStatus>().state.writeCharacteristic?.write([0xBB,0x0B,0x01]);
        });
        HapticFeedback.vibrate();
        _timer= Timer.periodic(timeout, (timer){
          setState(() {
            _time++;
          });
          if(_time>startConfig['style']!){
            _timer.cancel();
            HapticFeedback.vibrate();
            setState(() {
              _time=0;
              _runType='cold_wind';
              context.read<DeviceInfoStatus>().state.writeCharacteristic?.write([0xBB,0x0B,0x00]);
              context.read<DeviceInfoStatus>().state.writeCharacteristic?.write([0xBB,0x0C,0x01]);
            });
            _timer= Timer.periodic(timeout, (timer){
              setState(() {
                _time++;
              });
              if(_time>startConfig['cold_wind']!){
                _timer.cancel();
                HapticFeedback.vibrate();
                setState(() {
                  _time=0;
                  _runType='curling';
                  _runFlag=false;
                  context.read<DeviceInfoStatus>().state.writeCharacteristic?.write([0xBB,0x0C,0x00]);
                  context.read<DeviceInfoStatus>().state.writeCharacteristic?.write([0xBB,0x08,0x01]);
                });
              }
            });
          }
        });

      }
    });

  }
  _stopAutoStart(){
    _timer.cancel();
    setState(() {
      _time=0;
    });
  }
  _formatTime(time){
    if(time<10){
      return '0${time}';
    }else{
      return '${time}';
    }
  }
  @override
  Widget build(BuildContext context) {
    return Container(
      width: MediaQuery.of(context).size.width,
      constraints: BoxConstraints(minHeight: 100),
      margin: EdgeInsets.symmetric(vertical: 5, horizontal: 0),
      child: Padding(
          padding: EdgeInsets.symmetric(vertical: 0, horizontal: 4),
          child: Card(
              color: unitBgColor,
              child: Column(children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Container(
                      alignment: Alignment.topLeft,
                      padding: EdgeInsets.all(8),
                      margin: EdgeInsets.fromLTRB(0, 0, 0, 6),
                      child: Text(
                        'automatic_curling'.tr(),
                        style: TextStyle(fontSize: 16),
                      ),
                    ),
                    // Container(
                    //   child: IconButton(
                    //     icon: Icon(_runFlag?Icons.stop_circle_outlined:Icons.play_circle_outline_sharp, color: Colors.white,),
                    //     onPressed: () {
                    //       print('点击了图标${_runFlag}');
                    //       if(_runFlag){
                    //         _stopAutoStart();
                    //         setState(() {
                    //           _runFlag=false;
                    //         });
                    //       }else{
                    //         _autoStart();
                    //       }
                    //
                    //     },
                    //   ),
                    // ),
                  ]
                ),
                Container(
                  padding: EdgeInsets.symmetric(vertical: 0, horizontal: 8),
                  alignment: Alignment.topLeft,
                  child: Text('has_ready'.tr(),
                      style: TextStyle(fontSize: 16, color: Colors.white38)),
                ),
                Container(
                  padding: EdgeInsets.symmetric(vertical: 0, horizontal: 8),
                  alignment: Alignment.topLeft,
                  child: Text('ready_desc'.tr(),
                      style: TextStyle(fontSize: 16, color: Colors.white38)),
                ),
                if(_runFlag)
                  Container(
                    margin: EdgeInsets.symmetric(vertical: 12, horizontal: 8),
                    child: Column(
                      children: [
                        Row(
                          children: startConfig.entries.map((e) =>StatefulBuilder(
                            builder: ( context, setState) {
                              var color=Colors.white24;
                              if(e.key==_runType){
                                color=Colors.white;
                              }
                              return Expanded(
                                  child:Container(
                                    padding: EdgeInsets.all(16),
                                    child:  Column(
                                      children: [
                                        Text('${e.key}'.tr(),style: TextStyle(color: color)),
                                        Text('${e.value.toInt()}s',style: TextStyle(color: color)),
                                        if(e.key==_runType)
                                          Divider(
                                            color: Colors.white,
                                            height: 1,
                                            thickness: 1,
                                          ),
                                      ],
                                    ),
                                  )
                              );
                            },
                          )).toList(),
                        ),
                        Container(
                           child: Stack(
                             children: [
                               Container(
                                 margin: EdgeInsets.symmetric(vertical: 2, horizontal: 0),
                                 child: RotationTransition(
                                   turns: _animation,
                                   child:  Image(
                                     width: 120,
                                     height: 120,
                                     image: AssetImage('assets/img/fans.png'),
                                   ),
                                 )
                               ),
                               Positioned(
                                 //上下左右都居中
                                 left: 0,
                                 right: 0,
                                 top: 0,
                                 bottom: 0,
                                 child: Center(
                                   child: Text('00:${_formatTime(_time)}',style: TextStyle(color: Colors.white)),
                                 ),

                               )
                             ],
                           ),
                        )
                      ]
                    )
                  ),
                Container(
                  padding: EdgeInsets.symmetric(vertical: 12, horizontal: 8),
                  alignment: Alignment.center,
                  child: TextButton(
                    onPressed: () {
                      if(_runFlag) return;
                      _showSettingDialogs(startConfig);
                    },
                    style: ButtonStyle(
                      backgroundColor: WidgetStateProperty.all(Colors.white38),
                      // 设置宽度
                      fixedSize: WidgetStateProperty.all(
                          Size(MediaQuery.of(context).size.width - 100, 40)),
                      // 设置圆角
                      shape: WidgetStateProperty.all(RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(5.0),
                      )),
                    ),
                    child: Text('time_config_btn'.tr(),
                        style: TextStyle(fontSize: 16, color: Colors.white38)),
                  ),
                ),
              ]))),
    );
  }


}
